﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Data;

namespace APNotifications.Helper
{
    class IM
    {
        private wsAPjunktion.APjunktionInterface _wsAPjunktionInterface = new wsAPjunktion.APjunktionInterface();

        public IM(string wsURL)
        {                        
            _wsAPjunktionInterface.Url = wsURL;
        }

        public string GetMessageCount(int ApplicationId, int UserIdTo)
        {
            string messages = string.Empty;

            try
            {
                XmlNode xmlMessageCount = null;
                string result = string.Empty;

                if (_wsAPjunktionInterface.GetMessageCount(ApplicationId, UserIdTo, ref result, ref xmlMessageCount))
                {
                    foreach (XmlNode xn in xmlMessageCount)
                    {
                        messages += FormatMessage(xn.SelectSingleNode("Count").InnerText, xn.SelectSingleNode("UserNameFrom").InnerText);
                    }
                }
                else
                {
                    messages = result;
                }
            }
            catch (Exception ex)
            {
                messages = ex.Message;      
            }

            return messages;
        }

        public string GetMessages(int Rows,int ApplicationId, int UserId)
        {            
            string messages = string.Empty;

            try
            {
                XmlNode xmlMessages = null;
                string result = string.Empty;                

                if (_wsAPjunktionInterface.GetMessage(Rows, ApplicationId, UserId, ref result, ref xmlMessages))
                {
                    foreach (XmlNode xn in xmlMessages)
                    {
                        messages += FormatMessage(xn.SelectSingleNode("Message").InnerText, xn.SelectSingleNode("UserNameFrom").InnerText);
                    }
                }
                else
                {
                    messages = result;
                }
                
            }
            catch(Exception ex)
            {
                messages = ex.Message;      
            }

            return messages;

        }

        private string FormatMessage(string Message, string Name)
        {
            return Name + ": " + Message + "\n";
        }        
    }
}
